<template>
    <main>
        <!-- 顶部 标题  -->
        <van-nav-bar :title="isEdit ? '编辑地址' : '新增地址'" left-arrow @click-left="router.back()" />
        <van-address-edit :area-list="areaList" show-set-default show-search-result
            :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" :address-info="addressItem" />
    </main>
</template>

<script setup>
import { ref, onMounted } from "vue";
//三级联动的 地址数据
import { areaList } from "@vant/area-data";
import { addAddress, getAddressList, updateAddress } from "@/api/address";
import { showSuccessToast } from "vant";

import { useRouter, useRoute } from "vue-router";

let router = useRouter();
let route = useRoute();


//定义数据 区分编辑和新增
let isEdit = ref(!!route.query.id);

// 要回显的表单数据
let addressItem = ref({});

// 如果是编辑  则调接口 查询 地址列表
onMounted(async () => {
    if (isEdit.value) {
        // 拿到所有地址列表
        let arr = (await getAddressList({ limit: 100, page: 1 })).data.list;
        //console.log(arr);
        //拿到  id 为当前商品的地址
        //console.log(route.query.id);
        let addressData = arr.find((item) => item.id == route.query.id);
        // 改造为 组件 需要的数据   重置接口返回数据为表单组件所需要的数据
        addressItem.value = {
            id: addressData.id,
            name: addressData.name,
            tel: addressData.phone,
            province: addressData.province,
            city: addressData.city,
            county: addressData.town,
            addressDetail: addressData.detail,
            isDefault: !!addressData.is_default,
        };
    }
});

// 点击保存按钮
let onSave = async (value) => {
    console.log(value);
    // 配置 新增参数  重置表单数据格式为接口需要的格式
    let data = {
        is_default: value.isDefault ? 1 : 0,
        name: value.name,
        phone: value.tel,
        province: value.province,
        city: value.city,
        town: value.county,
        street: "默认值",
        detail: value.addressDetail,
    };

    if (isEdit.value) {
        // 编辑逻辑
        // 调用编辑接口
        await updateAddress({ ...data, id: route.query.id });
        showSuccessToast("编辑成功");
    } else {
        // 新增逻辑
        // 调用新增接口
        await addAddress(data);
        showSuccessToast("新增成功");
    }
    // 返回地址列表
    router.replace("/address-list");
};
</script>